import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "@/access/AccessEnum";
import checkAccess from "@/access/CheckAccess";

router.beforeEach(async (to, from, next) => {
  let loginUser = store.state.user.loginUser;

  // 如果之前为登录，则触发自动登录
  if (!loginUser || !loginUser.userRole) {
    await store.dispatch("user/getLoginUser");
    loginUser = store.state.user.loginUser;
  }

  // 获取当前访问的页面所需要的权限
  const needAccess = to.meta?.access ?? ACCESS_ENUM.NOT_LOGIN;
  console.log("needAccess{}", needAccess);
  console.log("loginUser{}", loginUser);

  // 如果当前页面需要权限，且当前用户没登录，则跳转到登录页面
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    // 如果当前用户没登录
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole === ACCESS_ENUM.NOT_LOGIN
    ) {
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    // 如果已经登录但是权限不足则跳转
    if (!checkAccess(loginUser, needAccess as string)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
